package com.scalar.chiptrack.operations.dataentry.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.dataentry.forms.DieBankReceiveForm;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.InTransitLots;
import com.scalar.chiptrack.operations.release.dao.RelaseDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * User: ChandraSekhar
 * Date: Jan 4, 2008
 * Time: 4:16:26 PM
 */
public class DieBankReceiveAction extends ChipTrackAction implements SessionKeys, AdaptorConstants
{
    private static final String ACTION_NAME = "/dieBankReceive.do";

    public ActionForward execute (ActionMapping mapping, ActionForm form,
                              HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        HashMap<String, String> errors          = new HashMap<String, String>();
		HashMap<String, String> info            = new HashMap<String, String>();
        String actionForword    = "success";
        String action           = request.getParameter ("action");
        DieBankReceiveForm dieBankReceiveForm = (DieBankReceiveForm)form;
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        ArrayList<InTransitLots> fabTransitLotList     = new ArrayList<InTransitLots>();
        ArrayList<InTransitLots> dbReceiveLotList      = new ArrayList<InTransitLots>();
        HttpSession session = request.getSession ();
        DBTransaction dbTranasaction    = null;
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        Calendar cal = Calendar.getInstance();
        int thisYear = cal.get( Calendar.YEAR );
        String yearLastDigit  = thisYear+"";
        yearLastDigit = yearLastDigit.substring( yearLastDigit.length()-1 );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME  );
            return ( mapping.findForward ( "login" ) );
        }

        if ( action == null )
        {
            action = "";
        }
        String processString = LOCATION_TYPE_FAB+ "," +LOCATION_TYPE_FAB_OPTION + "," +LOCATION_TYPE_DIE_BANK ;

        int fabProcessStepId        = -1;
        int fabOptionProcessStepId  = -1;

        if ( action.equals("") )
		{
            try
            {
                dieBankReceiveForm.setProcessStepId(0);
                dieBankReceiveForm.setLocationId(0);
                dieBankReceiveForm.setLotId(0);

                fabTransitLotList = DataEntryDAO.loadAllTransitLots( processString, "0", 0, LOCATION_TYPE_DIE_BANK, user.getVendorId(), 0  );

                if ( fabTransitLotList == null || fabTransitLotList.size() == 0 )
                {
                    info.put("No Fab Transit lots available" , null );
                }
                dieBankReceiveForm.setTransitLotsList( fabTransitLotList );

                request.setAttribute("lotsList", fabTransitLotList );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FAB, 0 ) );
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("nextLocationList",  RelaseDAO.loadProcessVendors( LOCATION_TYPE_DIE_BANK ) );
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
		else if ( action.equalsIgnoreCase ("search") )
		{
            actionForword = "search";
            String procssStepIdsString;
            try
            {
                if ( dieBankReceiveForm.getProcessStepId() > 0)
                {
                    fabProcessStepId = NewProductDAO.getForwardOrBackwardProcessstepId( dbTranasaction,dieBankReceiveForm.getProcessStepId(), 0, LOCATION_TYPE_FAB );
                    fabOptionProcessStepId = NewProductDAO.getForwardOrBackwardProcessstepId( dbTranasaction,dieBankReceiveForm.getProcessStepId(), 0, LOCATION_TYPE_FAB_OPTION );

                    procssStepIdsString = fabProcessStepId+","+fabOptionProcessStepId+","+dieBankReceiveForm.getProcessStepId();
                }
                else
                {
                    procssStepIdsString  = dieBankReceiveForm.getProcessStepId()+"";
                }

                fabTransitLotList = DataEntryDAO.loadAllTransitLots( processString, procssStepIdsString, dieBankReceiveForm.getLocationId(), LOCATION_TYPE_DIE_BANK, user.getVendorId(), dieBankReceiveForm.getLotId() );

                if ( fabTransitLotList == null || fabTransitLotList.size() == 0 )
                {
                    info.put("No Fab Transit lots available" , null );
                }
                dieBankReceiveForm.setTransitLotsList( fabTransitLotList );

                request.setAttribute("nextLocationList",  RelaseDAO.loadProcessVendors( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("lotsList", DataEntryDAO.loadAllTransitLots( processString, "0", 0, LOCATION_TYPE_DIE_BANK, user.getVendorId(), 0 ) );
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FAB, 0 ) );
            }
            catch(Exception e)
            {
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FAB, 0 ) );
                request.setAttribute("lotsList", DataEntryDAO.loadAllTransitLots( processString, "0", 0, LOCATION_TYPE_DIE_BANK, user.getVendorId(), 0 ) );
                e.printStackTrace();
                errors.put("Unable to search the transit lots" , null );
            }
        }
        else if ( action.equalsIgnoreCase("save") )
        {
        	actionForword = "save";
            InTransitLots inTransitLots = null;
            HashMap<String, String> nextLotNoMap        = new HashMap<String, String>();
            int incrementDigit  = 0;
            String vendorCode   = null;
            int generateLotNo   = -1;
            try
            {
                if ( dieBankReceiveForm.getTransitLotsList() != null && dieBankReceiveForm.getTransitLotsList().size() > 0 )
                {
                   for( int i=0; i < dieBankReceiveForm.getTransitLotsList().size(); i++)
                    {
                        inTransitLots = (InTransitLots)dieBankReceiveForm.getTransitLotsList().get(i);

                        if ( inTransitLots.isChecked() )
                        {
                            generateLotNo = DataEntryDAO.isGenerateLotNumber();  //CHECKING WHETHER THE CUSTOMER FLOW HAS lot NO GERATION

                            if ( generateLotNo > 0 )
                            {
                               inTransitLots.setDieBankLotNo( inTransitLots.getFabLotNumber() );
                            }
                            else
                            {
                                if ( LOCATION_TYPE_FAB.equalsIgnoreCase( inTransitLots.getProcessType() ) || LOCATION_TYPE_FAB_OPTION.equalsIgnoreCase( inTransitLots.getProcessType() ) )
                                {
                                    if ( nextLotNoMap.containsKey( inTransitLots.getDieBankLotNo() ) )
                                    {
                                        String key = inTransitLots.getDieBankLotNo();
                                        String value = (String)nextLotNoMap.get( inTransitLots.getDieBankLotNo() );
                                        vendorCode = inTransitLots.getVendorCode();
                                        incrementDigit = Integer.parseInt( value.substring( vendorCode.length()+ 1 ) ) + 1;

                                        if ( incrementDigit < 10 )
                                        {
                                            value = vendorCode + yearLastDigit + "00"+ incrementDigit;
                                        }
                                        else if (incrementDigit < 100 )
                                        {
                                            value = vendorCode + yearLastDigit + "0"+ incrementDigit;
                                        }
                                        else if (incrementDigit < 1000 )
                                        {
                                            value = vendorCode + yearLastDigit + incrementDigit;
                                        }

                                        while ( DataEntryDAO.isLotNumberExists(null, -1,-1, value, LOCATION_TYPE_DIE_BANK ) )
                                        {
                                            incrementDigit = incrementDigit + 1;

                                            if ( incrementDigit < 10 )
                                            {
                                                value = vendorCode + yearLastDigit + "00"+ incrementDigit;
                                            }
                                            else if (incrementDigit <100)
                                            {
                                                value = vendorCode + yearLastDigit + "0"+ incrementDigit;
                                            }
                                            else if (incrementDigit < 1000)
                                            {
                                                value = vendorCode + yearLastDigit + incrementDigit;
                                            }
                                        }
                                        inTransitLots.setDieBankLotNo( value ); //setting the Value
                                        nextLotNoMap.put( key, value);
                                    }
                                    else
                                    {
                                    	String key = inTransitLots.getDieBankLotNo();
                                        String value = inTransitLots.getDieBankLotNo();
                                        vendorCode = inTransitLots.getVendorCode();
                                        incrementDigit = Integer.parseInt( value.substring( vendorCode.length()+ 1 ) );

                                        while( DataEntryDAO.isLotNumberExists(null, -1,-1, value, LOCATION_TYPE_DIE_BANK ) )
                                        {
                                        	incrementDigit = incrementDigit + 1;				
                                            if ( incrementDigit < 10 )
                                            {
                                                value = vendorCode + yearLastDigit + "00"+ incrementDigit;
                                            }
                                            else if (incrementDigit <100)
                                            {
                                                value = vendorCode + yearLastDigit + "0"+ incrementDigit;
                                            }
                                            else if (incrementDigit < 1000)
                                            {
                                                value = vendorCode + yearLastDigit + incrementDigit;
                                            }
                                        }
                                        inTransitLots.setDieBankLotNo( value );
                                        nextLotNoMap.put( key, value );
                                    }
                                }
                                else
                                {
                                    inTransitLots.setDieBankLotNo( inTransitLots.getLotNumber() );
                                }
                            }

                            if ( inTransitLots.getCheckedWaferIdsAsString() == null || inTransitLots.getCheckedWaferIdsAsString().equals("") )
                            {
                               inTransitLots.setCheckedWaferIdsAsString( inTransitLots.getWaferId() );
                            }
                            
                            dbReceiveLotList.add( inTransitLots );
                        }
                    }
                }
                dieBankReceiveForm.setConfirmTransitLotsList( dbReceiveLotList );

                saveToken( request );
            }
            catch(Exception e)
            {
                request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
                request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FAB, 0 ) );
                request.setAttribute("lotsList", DataEntryDAO.loadAllTransitLots( processString, "0", 0, LOCATION_TYPE_DIE_BANK, user.getVendorId(), 0 ) );
                e.printStackTrace();
                errors.put("Unable to save the transit lots" , null );
            }
        }
        else if ( action.equalsIgnoreCase("confirm") )
        {
            actionForword = "success";
            try
            {
                if ( isTokenValid( request ) )
                {                       
                    DataEntryDAO.saveDieBankReceiveInfo( dbTranasaction, dieBankReceiveForm.getConfirmTransitLotsList(), user.getUserName() );

                    DataEntryDAO.updateDiebankReceiveLotBinInfo( dieBankReceiveForm.getConfirmTransitLotsList(), "DieBankReceive" );

                    resetToken ( request );

                    info.put("Lots received to DieBank Successlly", null);
                }
                else
                {
                    errors.put("Invalid Request" , null );
                }
            }
            catch(Exception e)
            {
               e.printStackTrace();
               errors.put("Unable to receive the lots to Diebank" , null );
            }

            dieBankReceiveForm.setProcessStepId(0);
            dieBankReceiveForm.setLocationId(0);
            dieBankReceiveForm.setLotId(0);
            dieBankReceiveForm.setTransitLotsList( null);
            
            request.setAttribute("lotsList", DataEntryDAO.loadAllTransitLots( processString, "0", 0, LOCATION_TYPE_DIE_BANK, user.getVendorId(), 0 ) );
            request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessType( LOCATION_TYPE_DIE_BANK ) );
            request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FAB, 0 ) );
        }
        
        return (mapping.findForward ( actionForword ) );
    }
}
